package com.ruoyi.web.controller.shop.service.Impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.entity.DO.product.*;
import com.ruoyi.common.entity.VO.shop.ShopProductSearchVO;
import com.ruoyi.common.entity.VO.shop.ShopProductVO;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.IBackProductMapper;
import com.ruoyi.system.mapper.IBackShopProductMapper;
import com.ruoyi.web.controller.product.mapper.IBackProductCategoryLinkMapper;
import com.ruoyi.web.controller.product.mapper.IBackProductCategoryMapper;
import com.ruoyi.web.controller.shop.mapper.IBackShopProductAttrMapper;
import com.ruoyi.web.controller.shop.mapper.IBackShopProductCouponLinkMapper;
import com.ruoyi.web.controller.shop.service.IBackShopProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;


@Service
public class BackShopProductServiceImpl implements IBackShopProductService {

    @Resource
    private IBackProductCategoryMapper backProductCategoryMapper;

    @Resource
    private IBackProductCategoryLinkMapper backProductCategoryLinkMapper;

    @Resource
    private IBackShopProductMapper backShopProductMapper;

    @Resource
    private IBackShopProductCouponLinkMapper backShopProductCouponLinkMapper;

    @Resource
    private IBackProductMapper backProductMapper;

    @Resource
    private IBackShopProductAttrMapper backShopProductAttrMapper;

    @Override
    public List<ShopProductVO> searchList(ShopProductSearchVO shopProductSearchVO) {
        shopProductSearchVO.setIsDelete(0);
        return backShopProductMapper.searchList(shopProductSearchVO);
    }

    @Override
    public List<ShopProductAttributeDO> searchAttrList(ShopProductSearchVO shopProductSearchVO) {
        Example example = new Example(ShopProductAttributeDO.class);
        example.createCriteria().andEqualTo("productId", shopProductSearchVO.getProductId());
        example.createCriteria().andEqualTo("shopId", shopProductSearchVO.getShopId());
        example.createCriteria().andEqualTo("isDelete", 0);
        return backShopProductAttrMapper.selectByExample(example);
    }

    @Override
    public ShopProductVO getDetailById(Long linkId) {
        return backShopProductMapper.getDetailById(linkId);
    }

    @Override
    @Transactional
    public void add(ShopProductVO shopProductVO) {
        ProductDO productDO = new ProductDO();
        if (StringUtils.isEmpty(shopProductVO.getCategoryIds())) {
            throw new BusinessException("请至少选择一个商品分类!");
        }
        productDO.setShopId(shopProductVO.getShopId());
        productDO.setProductSn(NumberUtils.generateCode(8));
        productDO.setProductType(shopProductVO.getProductType());
        productDO.setProductName(shopProductVO.getProductName());
        productDO.setCoverUrl(shopProductVO.getCoverUrl());
        productDO.setOrderNum(1);
        productDO.setMemo(shopProductVO.getMemo());
        productDO.setIsDelete(0);
        productDO.setPrice(shopProductVO.getProductPrice());
        productDO.setStock(shopProductVO.getStock());
        productDO.setIsEnable(shopProductVO.getIsEnable());
        productDO.setCreateTime(shopProductVO.getCreateTime());
        productDO.setCreateBy(shopProductVO.getCreateBy());
        //组装商品分类字段
        List<String> productCategoryNameList = backProductCategoryMapper.getCategoryNameList(shopProductVO.getCategoryIds());
        String productCategory = StringUtils.join(productCategoryNameList.toArray(), ',');
        productDO.setProductCategory(productCategory);
        backProductMapper.insertSelective(productDO);
        //插入商品分类关联表
        Long[] categoryIdArr = Convert.toLongArray(shopProductVO.getCategoryIds());
        for (Long categoryId : categoryIdArr
        ) {
            ProductCategoryLinkDO categoryLinkDO = new ProductCategoryLinkDO();
            categoryLinkDO.setCategoryId(categoryId);
            categoryLinkDO.setProductId(productDO.getId());
            categoryLinkDO.setCreateTime(shopProductVO.getCreateTime());
            categoryLinkDO.setCreateBy(shopProductVO.getCreateBy());
            backProductCategoryLinkMapper.insertSelective(categoryLinkDO);
        }
        if (1 == productDO.getProductType()) {
            for (Long couponId : shopProductVO.getCouponIdArr()
            ) {
                ShopProductCouponLinkDO couponLinkDO = new ShopProductCouponLinkDO();
                couponLinkDO.setCouponId(couponId);
                couponLinkDO.setProductId(productDO.getId());
                couponLinkDO.setShopId(shopProductVO.getShopId());
                couponLinkDO.setModuleId(SysConfigConstants.SystemModuleEnum.CREDIT.getValue());
                backShopProductCouponLinkMapper.insertSelective(couponLinkDO);
            }
        }
        //插入站点商品表
        ShopProductDO shopProductDO = new ShopProductDO();
        shopProductDO.setShopId(shopProductVO.getShopId());
        shopProductDO.setProductId(productDO.getId());
        shopProductDO.setProductPrice(shopProductVO.getProductPrice());
        shopProductDO.setOrderNum(shopProductVO.getOrderNum());
        shopProductDO.setSale(0);
        shopProductDO.setIsEnable(shopProductVO.getIsEnable());
        shopProductDO.setIsDelete(0);
        shopProductDO.setCreateTime(shopProductVO.getCreateTime());
        shopProductDO.setCreateBy(shopProductVO.getCreateBy());
        backShopProductMapper.insertSelective(shopProductDO);
    }

    @Override
    public int edit(ShopProductVO shopProductVO) {
        //批量上下架
        if (StringUtils.isNotEmpty(shopProductVO.getIds())) {
            shopProductVO.setIdArr(Convert.toLongArray(shopProductVO.getIds()));
            if (shopProductVO.getIdArr().length > 1) {
                return backShopProductMapper.multiUpdate(shopProductVO);
            } else {
                shopProductVO.setId(shopProductVO.getIdArr()[0]);
            }
        }
        ShopProductDO shopProductDO = backShopProductMapper.selectByPrimaryKey(shopProductVO.getId());
        if (shopProductDO == null) {
            throw new BusinessException("编辑数据不存在!");
        }
        if (shopProductDO.getIsDelete() == 1) {
            throw new BusinessException("编辑的数据已被删除!");
        }
        ProductDO productDO = backProductMapper.selectByPrimaryKey(shopProductDO.getProductId());
        if (productDO == null || productDO.getIsEnable() == 0 || productDO.getIsDelete() == 1) {
            throw new BusinessException("总平台已下架该条数据!");
        }
        if (!productDO.getSystemModule().equals(shopProductVO.getSystemModule())) {
            throw new BusinessException("没有该条数据的编辑权限!");
        }
        if (StringUtils.isNotEmpty(shopProductVO.getProductName())) {
            ProductDO productUpdateDO = new ProductDO();
            productUpdateDO.setId(shopProductDO.getProductId());
            productUpdateDO.setProductName(shopProductVO.getProductName());
            backProductMapper.updateByPrimaryKeySelective(productUpdateDO);
        }
        shopProductDO.setIsEnable(shopProductVO.getIsEnable());
        shopProductDO.setProductPrice(shopProductVO.getProductPrice());
        shopProductDO.setOrderNum(shopProductVO.getOrderNum());
        shopProductDO.setIsEnable(shopProductVO.getIsEnable());
        shopProductDO.setShopRemark(shopProductVO.getShopRemark());
        return backShopProductMapper.updateByPrimaryKeySelective(shopProductDO);
    }

    @Override
    public int creditEdit(ShopProductVO shopProductVO) {
        //批量上下架
        if (StringUtils.isNotEmpty(shopProductVO.getIds())) {
            shopProductVO.setIdArr(Convert.toLongArray(shopProductVO.getIds()));
            if (shopProductVO.getIdArr().length > 1) {
                return backShopProductMapper.multiUpdate(shopProductVO);
            } else {
                shopProductVO.setId(shopProductVO.getIdArr()[0]);
            }
        }
        ShopProductDO shopProductDO = backShopProductMapper.selectByPrimaryKey(shopProductVO.getId());
        if (shopProductDO == null || !shopProductDO.getShopId().equals(shopProductVO.getShopId())) {
            throw new BusinessException("编辑数据不存在!");
        }
        if (shopProductDO.getIsDelete() == 1) {
            throw new BusinessException("编辑的数据已被删除!");
        }
        ProductDO productDO = backProductMapper.selectByPrimaryKey(shopProductDO.getProductId());
        if (productDO == null || productDO.getIsEnable() == 0 || productDO.getIsDelete() == 1) {
            throw new BusinessException("总平台已下架该条数据!");
        }
        if (!productDO.getSystemModule().equals(shopProductVO.getSystemModule())) {
            throw new BusinessException("没有该条数据的编辑权限!");
        }

        productDO.setProductName(shopProductVO.getProductName());
        productDO.setProductType(shopProductVO.getProductType());
        productDO.setCoverUrl(shopProductVO.getCoverUrl());
        productDO.setMemo(shopProductVO.getMemo());
        productDO.setStock(shopProductVO.getStock());
        productDO.setUpdateTime(shopProductVO.getUpdateTime());
        productDO.setUpdateBy(shopProductVO.getUpdateBy());
        //组装商品分类字段
        if (StringUtils.isNotEmpty(shopProductVO.getCategoryIds())) {
            List<String> productCategoryNameList = backProductCategoryMapper.getCategoryNameList(shopProductVO.getCategoryIds());
            String productCategory = StringUtils.join(productCategoryNameList.toArray(), ',');
            productDO.setProductCategory(productCategory);
            backProductCategoryLinkMapper.deleteByProductId(productDO.getId());
            //插入商品分类关联表
            Long[] categoryIdArr = Convert.toLongArray(shopProductVO.getCategoryIds());
            for (Long categoryId : categoryIdArr
            ) {
                ProductCategoryLinkDO categoryLinkDO = new ProductCategoryLinkDO();
                categoryLinkDO.setCategoryId(categoryId);
                categoryLinkDO.setProductId(productDO.getId());
                categoryLinkDO.setCreateTime(shopProductVO.getCreateTime());
                categoryLinkDO.setCreateBy(shopProductVO.getCreateBy());
                backProductCategoryLinkMapper.insertSelective(categoryLinkDO);
            }
        }
        backProductMapper.updateByPrimaryKeySelective(productDO);
        //清空商品分类关联表
        shopProductDO.setIsEnable(shopProductVO.getIsEnable());
        shopProductDO.setProductPrice(shopProductVO.getProductPrice());
        shopProductDO.setOrderNum(shopProductVO.getOrderNum());
        shopProductDO.setIsEnable(shopProductVO.getIsEnable());
        shopProductDO.setShopRemark(shopProductVO.getShopRemark());
        backShopProductCouponLinkMapper.clear(productDO.getShopId(), productDO.getId());
        if (null != productDO.getProductType() && 1 == productDO.getProductType()) {
            for (Long couponId : shopProductVO.getCouponIdArr()
            ) {
                ShopProductCouponLinkDO couponLinkDO = new ShopProductCouponLinkDO();
                couponLinkDO.setCouponId(couponId);
                couponLinkDO.setProductId(productDO.getId());
                couponLinkDO.setShopId(shopProductVO.getShopId());
                couponLinkDO.setModuleId(SysConfigConstants.SystemModuleEnum.CREDIT.getValue());
                backShopProductCouponLinkMapper.insertSelective(couponLinkDO);
            }
        }
        return backShopProductMapper.updateByPrimaryKeySelective(shopProductDO);
    }

    @Override
    public int attrEdit(ShopProductAttributeDO shopProductAttributeDO) {
        ShopProductAttributeDO attrInfo = backShopProductAttrMapper.selectByPrimaryKey(shopProductAttributeDO.getId());
        if (1 == attrInfo.getIsDelete()) {
            throw new BusinessException("数据已删除，请刷新后重试！");
        }
        if(StringUtils.isNotEmpty(shopProductAttributeDO.getAttrName())){
            String isUnique = checkProductAttrNameUnique(shopProductAttributeDO);
            if(!Constants.SUCCESS.equals(isUnique)){
                throw new BusinessException("油枪号【"+shopProductAttributeDO.getAttrName()+"】已存在");
            }
        }
        shopProductAttributeDO.setProductId(null);
        shopProductAttributeDO.setShopId(null);
        shopProductAttributeDO.setCreateTime(null);
        shopProductAttributeDO.setCreateBy(null);
        return backShopProductAttrMapper.updateByPrimaryKeySelective(shopProductAttributeDO);
    }


    @Override
    @Transactional
    public int creditRemove(ShopProductVO shopProductVO) {
        Long[] idArr = Convert.toLongArray(shopProductVO.getIds());
        for (Long id : idArr
        ) {
            ShopProductDO one = backShopProductMapper.selectByPrimaryKey(id);
            if (null == one || 1 == one.getIsDelete()) {
                throw new BusinessException("商品已删除，请刷新！");
            }
            if (1 == one.getIsEnable()) {
                throw new BusinessException("请先下架该商品！");
            }
            backShopProductMapper.deleteByProductId(one.getProductId());
            ProductDO productOne = backProductMapper.selectByPrimaryKey(one.getProductId());
            if (null != productOne && SysConfigConstants.SystemModuleEnum.CREDIT.getValue() != productOne.getSystemModule()) {
                throw new BusinessException("商品已删除，请刷新！！");
            }
            backProductMapper.deleteProductById(one.getProductId());
        }
        return 1;
    }

    @Override
    public int attrRemove(ShopProductAttributeDO shopProductAttributeDO) {
        ShopProductAttributeDO attrInfo = backShopProductAttrMapper.selectByPrimaryKey(shopProductAttributeDO.getId());
        if (attrInfo == null || attrInfo.getIsDelete() == 1) {
            return 0;
        }
        if (attrInfo.getIsEnable() != 0) {
            throw new BusinessException("请先停用再删除！");
        }
        if (!attrInfo.getShopId().equals(shopProductAttributeDO.getShopId())) {
            return 0;
        }
        return backShopProductAttrMapper.remove(attrInfo.getId());
    }

    @Override
    public String checkProductAttrNameUnique(ShopProductAttributeDO shopProductAttributeDO) {
        Long attrId = StringUtils.isNull(shopProductAttributeDO.getId()) ? -1L : shopProductAttributeDO.getId();
        Long existId = backShopProductAttrMapper.getIdByAttrName(shopProductAttributeDO.getShopId(), shopProductAttributeDO.getAttrName());
        if (existId != null && !attrId.equals(existId)) {
            return Constants.FAIL;
        }
        return Constants.SUCCESS;
    }
}
